package com.beeantec.jnrerc.modules.member.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beeantec.jnrerc.core.annon.LogInject;
import com.beeantec.jnrerc.core.api.ApiRest;
import com.beeantec.jnrerc.core.api.controller.BaseController;
import com.beeantec.jnrerc.core.enums.MissionStateEnum;
import com.beeantec.jnrerc.core.utils.RandomUtils;
import com.beeantec.jnrerc.dto.MemberVo;
import com.beeantec.jnrerc.dto.request.*;
import com.beeantec.jnrerc.dto.response.*;
import com.beeantec.jnrerc.entity.*;
import com.beeantec.jnrerc.modules.course.service.CourseMemberStudyLogService;
import com.beeantec.jnrerc.modules.course.service.GroupMemberService;
import com.beeantec.jnrerc.modules.course.service.GroupService;
import com.beeantec.jnrerc.modules.member.service.MemberService;
import com.beeantec.jnrerc.modules.mission.service.MissionService;
import com.beeantec.jnrerc.modules.mission.service.TeamMissionService;
import com.beeantec.jnrerc.modules.user.service.AdminService;
import com.beeantec.jnrerc.modules.user.service.MemberExamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Anthony
 */
@Api(tags={"系统管理员"})
@RestController
@RequestMapping("/api/admin")
public class AdminController extends BaseController {
    @Autowired
    private AdminService adminService;


    @Autowired
    private MemberService memberService;


    @Autowired
    private MemberExamService memberExamService;


    @Autowired
    private MissionService missionService;

    @Autowired
    private TeamMissionService teamMissionService;

    @Autowired
    GroupService groupService;

    @Autowired
    CourseMemberStudyLogService courseMemberStudyLogService;

    @Autowired
    GroupMemberService groupMemberService;

    /**
     * 管理后台登录
     * @return
     */
    @LogInject(title = "管理后台登录")
    @CrossOrigin
    @ApiOperation(value = "管理后台登录")
    @RequestMapping(value = "/login", method = {RequestMethod.POST})
    public ApiRest<String> login(@RequestBody AdminLoginReqDTO loginReqDTO) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Admin::getAccount,loginReqDTO.getAccount());
        Admin admin = adminService.getOne(queryWrapper);
        if (null==admin){
         return    failure("账号不存在");
        }
        if (!ObjectUtil.contains(admin.getPassword(),loginReqDTO.getPassword())){
            return failure("密码错误");
        }
        return super.success("登录成功");
    }



    /**
     * 修改登录密码
     * @return
     */
    @LogInject(title = "修改登录密码")
    @CrossOrigin
    @ApiOperation(value = "修改登录密码")
    @RequestMapping(value = "/change/password", method = {RequestMethod.POST})
    public ApiRest<String> login(@RequestBody AdminChangeReqDTO loginReqDTO) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Admin::getAccount,loginReqDTO.getAccount());
        Admin admin = adminService.getOne(queryWrapper);
        if (null==admin){
            return    failure("账号不存在");
        }
        if (!ObjectUtil.contains(admin.getPassword(),loginReqDTO.getOldPassword())){
            return failure("密码错误");
        }
        admin.setPassword(loginReqDTO.getNewPassword());
       boolean result = adminService.updateById(admin);
       if (!result){
           return super.failure("修改失败");
       }
        return super.success("修改成功");
    }


    /**
     * 获取用户列表
     * @return
     */
    @LogInject(title = "获取用户列表")
    @CrossOrigin
    @ApiOperation(value = "获取用户列表")
    @RequestMapping(value = "/list", method = {RequestMethod.GET})
    public ApiRest<IPage<Member>> list(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.lambda().ne(Member::getDepId,-1);
        Page<Member> page = new Page<>(pageNum, pageSize);
        IPage<Member> iPage= memberService.getBaseMapper().selectPage(page,memberQueryWrapper);
        return success(iPage);
    }



    /**
     * 获取用户列表
     * @return
     */
    @LogInject(title = "更新用户部门和职位")
    @CrossOrigin
    @ApiOperation(value = "更新用户部门和职位")
    @RequestMapping(value = "/updateDepAndJob", method = {RequestMethod.POST})
    public ApiRest<String> update(@RequestBody MemberDepJobSetDTO memberDepJobSetDTO) {
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.lambda().eq(Member::getMemberId,memberDepJobSetDTO.getMemberId());
        Member member = memberService.getOne(memberQueryWrapper);
        if (null==member){
            return failure("用户不存在");
        }
        member.setDepId(memberDepJobSetDTO.getDepId());
        member.setJobId(memberDepJobSetDTO.getJobId());
        member.setMemberType(1);
        if (memberService.saveOrUpdate(member)){
            return success("更新成功");
        }
        return failure("更新失败");
    }


    /**
     * 设置用户积分
     * @return
     */
    @LogInject(title = "设置用户积分")
    @CrossOrigin
    @ApiOperation(value = "设置用户积分")
    @RequestMapping(value = "/add/integral", method = {RequestMethod.POST})
    public ApiRest<String> updateIntegral(@RequestBody AddIntegralReqDTO addIntegralReqDTO) {
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.lambda().eq(Member::getMemberId,addIntegralReqDTO.getMemberId());
        Member member = memberService.getOne(memberQueryWrapper);
        if (null==member){
            return failure("用户不存在");
        }
        member.setIntegral(addIntegralReqDTO.getIntegral());
        if (memberService.saveOrUpdate(member)){
            return success("更新成功");
        }
        return failure("更新失败");
    }


    /**
     * 设置用户魅力值
     * @return
     */
    @LogInject(title = "设置用户魅力值")
    @CrossOrigin
    @ApiOperation(value = "设置用户魅力值")
    @RequestMapping(value = "/add/charm", method = {RequestMethod.POST})
    public ApiRest<String> updateCharm(@RequestBody AddCharmReqDTO charmReqDTO) {
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.lambda().eq(Member::getMemberId,charmReqDTO.getMemberId());
        Member member = memberService.getOne(memberQueryWrapper);
        if (null==member){
            return failure("用户不存在");
        }
        member.setCharm(charmReqDTO.getCharm());
        if (memberService.saveOrUpdate(member)){
            return success("更新成功");
        }
        return failure("更新失败");
    }



    @LogInject(title = "后台更新用户部门和职位")
    @CrossOrigin
    @ApiOperation(value = "后台更新用户部门和职位")
    @RequestMapping(value = "/update/depandjob", method = {RequestMethod.POST})
    public ApiRest<String> updatedepjob(@RequestBody MemberDepJobSetDTO memberDepJobSetDTO) {
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.lambda().eq(Member::getMemberId,memberDepJobSetDTO.getMemberId());
        Member member = memberService.getOne(memberQueryWrapper);
        if (null==member){
            return failure("用户不存在");
        }
        member.setDepId(memberDepJobSetDTO.getDepId());
        member.setJobId(memberDepJobSetDTO.getJobId());
        member.setMemberType(1);
        if (memberService.saveOrUpdate(member)){
            return success("更新成功");
        }
        return failure("更新失败");
    }



    /**
     * 获取用户列表
     * @return
     */
    @LogInject(title = "后台更新用户头像")
    @CrossOrigin
    @ApiOperation(value = "后台更新用户头像")
    @RequestMapping(value = "/update/headpic", method = {RequestMethod.POST})
    public ApiRest<String> update(@RequestBody MemberHeadUpdateDTO memberHeadUpdateDTO) {
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.lambda().eq(Member::getMemberId,memberHeadUpdateDTO.getMemberId());
        Member member = memberService.getOne(memberQueryWrapper);
        if (null==member){
            return failure("用户不存在");
        }
        member.setAvatarUrl(memberHeadUpdateDTO.getHeadPic());
        if (memberService.saveOrUpdate(member)){
            return success("更新成功");
        }
        return failure("更新失败");
    }

    /**
     * 根据部门获取用户列表
     * @return
     */
    @CrossOrigin
    @ApiOperation(value = "根据部门获取用户列表")
    @RequestMapping(value = "/memberList", method = {RequestMethod.GET})
    public ApiRest<List<Member>> getMemberListByDepId(@RequestParam("depId") Integer depId) {
        List<Member> memberList = new ArrayList<>();
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Member::getDepId,depId).ne(Member::getMemberId,0);
        memberList = memberService.list(queryWrapper);
        return super.success(memberList);
    }


    /**
     * 获取用户列表
     * @return
     */
    @LogInject(title = "录入内部人员")
    @CrossOrigin
    @ApiOperation(value = "录入内部人员")
    @RequestMapping(value = "/addMember", method = {RequestMethod.GET})
    public ApiRest<String> addMember(String phone, String nickName, Integer gender, String avatarUrl) {
        Member member = new Member();
        member.setPhone(phone);
        member.setAvatarUrl(avatarUrl);
        member.setNickName(nickName);
        member.setDepId(0);
        member.setMemberType(1);
        member.setExp(0);
        member.setGender(gender);
        member.setIntegral(0);
        member.setJobId(0);
        member.setCharm(0);
        if (memberService.saveOrUpdate(member)) {
            return success("添加成功");
        }
        return failure("添加失败");
    }





    /**
     * 获取用户列表
     * @return
     */
    @LogInject(title = "根据姓名搜索用户")
    @CrossOrigin
    @ApiOperation(value = "根据姓名搜索用户")
    @RequestMapping(value = "/searchMember", method = {RequestMethod.GET})
    public ApiRest<List<Member>> search(@RequestParam("name") String name) {
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.lambda().like(Member::getNickName,name).ne(Member::getDepId,-1);
        List<Member> memberList = new ArrayList<>();
        memberList = memberService.list(memberQueryWrapper);

        return success(memberList);
    }


    /**
     * 获取任务列表
     * @return
     */
    @LogInject(title = "管理员获取任务列表")
    @CrossOrigin
    @ApiOperation(value = "管理员获取任务列表")
    @RequestMapping(value = "/mission/list", method = {RequestMethod.GET})
    public ApiRest<List<MissionRespDTO>> listMission(@RequestParam("state") Integer state, @RequestParam("type") Integer type) {
        List<MissionRespDTO> respDTOList = new ArrayList<>();
        List<Mission> missionList = new ArrayList<>();
        if (type ==-1){
            if (state==0){
                QueryWrapper<Mission> missionQueryWrapper = new QueryWrapper<>();
                missionQueryWrapper.lambda().orderByDesc(Mission::getCreateTime);
                missionList = missionService.list(missionQueryWrapper);
            }else if (state==1){
                QueryWrapper<Mission> missionQueryWrapper = new QueryWrapper<>();
                missionQueryWrapper.lambda()
                        .ne(Mission::getStatus,MissionStateEnum.RELEASE.getCode())
                        .ne(Mission::getStatus,MissionStateEnum.ASSIGN_REWARDS.getCode()).orderByDesc(Mission::getCreateTime);
                missionList = missionService.list(missionQueryWrapper);
            }else if (state==2){
                QueryWrapper<Mission> missionQueryWrapper = new QueryWrapper<>();
                missionQueryWrapper.lambda()
                        .eq(Mission::getStatus,MissionStateEnum.ASSIGN_REWARDS.getCode()).orderByDesc(Mission::getCreateTime);
                missionList = missionService.list(missionQueryWrapper);
            }
        }else {
            if (state==0){
                QueryWrapper<Mission> missionQueryWrapper = new QueryWrapper<>();
                missionQueryWrapper.lambda().eq(Mission::getType,type).orderByDesc(Mission::getCreateTime);
                missionList = missionService.list(missionQueryWrapper);
            }else if (state==1){
                QueryWrapper<Mission> missionQueryWrapper = new QueryWrapper<>();
                missionQueryWrapper.lambda().eq(Mission::getType,type)
                        .ne(Mission::getStatus,MissionStateEnum.RELEASE.getCode())
                        .ne(Mission::getStatus,MissionStateEnum.ASSIGN_REWARDS.getCode()).orderByDesc(Mission::getCreateTime);
                missionList = missionService.list(missionQueryWrapper);
            }else if (state==2){
                QueryWrapper<Mission> missionQueryWrapper = new QueryWrapper<>();
                missionQueryWrapper.lambda().eq(Mission::getType,type)
                        .eq(Mission::getStatus,MissionStateEnum.ASSIGN_REWARDS.getCode()).orderByDesc(Mission::getCreateTime);
                missionList = missionService.list(missionQueryWrapper);
            }
        }

        for (Mission mission:missionList){
            MissionRespDTO missionRespDTO = new MissionRespDTO();
            missionRespDTO.setMission(mission);
            QueryWrapper<TeamMission> teamMissionQueryWrapper = new QueryWrapper<>();
            teamMissionQueryWrapper.lambda().eq(TeamMission::getMissionId,mission.getId());
            List<TeamMission> teamMissionList = new ArrayList<>();
            teamMissionList = teamMissionService.list(teamMissionQueryWrapper);
            missionRespDTO.setCount(teamMissionList.size());
            respDTOList.add(missionRespDTO);
        }
        return success(respDTOList);
    }



    /**
     * 获取用户考试记录
     * @return
     */
    @LogInject(title = "获取用户考试记录")
    @CrossOrigin
    @ApiOperation(value = "获取用户考试记录(传-1查所有的)")
    @RequestMapping(value = "/getMemberExamRecord", method = {RequestMethod.GET})
    public ApiRest<IPage<MemberExam>> search(@RequestParam("memberId") Integer memberId
    ,@RequestParam("pageNum") Integer pageNum,@RequestParam("pageSize") Integer pageSize) {
        QueryWrapper<MemberExam> memberQueryWrapper = new QueryWrapper<>();
        if (memberId!=-1){
            memberQueryWrapper.lambda().eq(MemberExam::getUserId,memberId);
        }
        Page<MemberExam> page = new Page<>(pageNum, pageSize);
        IPage<MemberExam> iPage= memberExamService.getBaseMapper().selectPage(page,memberQueryWrapper);
        return success(iPage);
    }

    /**
     * 获取用户考试记录
     * @return
     */
    @LogInject(title = "获取用户考试记录V2")
    @CrossOrigin
    @ApiOperation(value = "获取用户考试记录(传-1查所有的)")
    @RequestMapping(value = "/v2/getMemberExamRecord", method = {RequestMethod.GET})
    public ApiRest<IPage<AdminExamRecRespDTO>> searchV2(@RequestParam("memberId") Integer memberId
            ,@RequestParam("pageNum") Integer pageNum,@RequestParam("pageSize") Integer pageSize) {

        IPage<AdminExamRecRespDTO> iPage = memberExamService.admin_paging(pageNum,pageSize,memberId);
        return success(iPage);
    }


    /**
     * 获取用户学习记录
     * @return
     */
    @LogInject(title = "获取用户学习记录V2")
    @CrossOrigin
    @ApiOperation(value = "获取用户学习记录(传-1查所有的)")
    @RequestMapping(value = "/v2/getMemberStudyRecord", method = {RequestMethod.GET})
    public ApiRest<IPage<AdminStudyRecRespDTO>> searchStudyLog(@RequestParam("memberId") Integer memberId
            , @RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {

        IPage<AdminStudyRecRespDTO> iPage = courseMemberStudyLogService.admin_paging(pageNum,pageSize,memberId);
        return success(iPage);
    }




    /**
     * 删除学习小组
     *
     * @param groupId
     * @return
     */
    @ApiOperation(value = "删除学习小组", notes = "删除学习小组")
    @RequestMapping(value = "/removeGroup", method = RequestMethod.GET)
    public ApiRest<String> removeCourse(@RequestParam("groupId") Long groupId) {
        if (!groupService.removeById(groupId)){
            return failure("删除学习小组失败");
        }
        QueryWrapper<GroupMember> groupMemberQueryWrapper = new QueryWrapper<>();
        groupMemberQueryWrapper.lambda().eq(GroupMember::getGroupId,groupId.intValue());
        groupMemberService.remove(groupMemberQueryWrapper);
        return success("删除成功");
    }

}
